package controllers

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"library/models"
)

// 获取所有用户列表
func GetUsers(c *gin.Context) {
	var users []models.User
	DB.Find(&users)
	c.HTML(http.StatusOK, "user_list.html", gin.H{"Users": users})
}

// 显示添加用户页面
func ShowAddUserPage(c *gin.Context) {
	c.HTML(http.StatusOK, "user_add.html", nil)
}

// 添加用户提交
func AddUser(c *gin.Context) {
	name := c.PostForm("name")
	email := c.PostForm("email")
	phone := c.PostForm("phone")
	user := models.User{Name: name, Email: email, Phone: phone}
	DB.Create(&user)

	// 操作日志
	log := models.Log{Action: "添加用户: " + name, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/users")
}

// 显示编辑用户页面
func ShowEditUserPage(c *gin.Context) {
	id := c.Param("id")
	var user models.User
	DB.First(&user, id)
	c.HTML(http.StatusOK, "user_edit.html", gin.H{"User": user})
}

// 编辑用户提交
func EditUser(c *gin.Context) {
	id := c.Param("id")
	name := c.PostForm("name")
	email := c.PostForm("email")
	phone := c.PostForm("phone")

	var user models.User
	DB.First(&user, id)
	user.Name = name
	user.Email = email
	user.Phone = phone
	DB.Save(&user)

	// 操作日志
	log := models.Log{Action: "编辑用户: " + name, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/users")
}

// 删除用户
func DeleteUser(c *gin.Context) {
	id := c.Param("id")
	var user models.User
	DB.First(&user, id)
	DB.Delete(&user)

	// 操作日志
	log := models.Log{Action: "删除用户: " + user.Name, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/users")
}
